package com.sync.platform.controller;

import com.sync.platform.service.DatabaseConfigService;
import com.sync.platform.service.ServerConfigService;
import com.sync.platform.service.SyncTaskLogService;
import com.sync.platform.service.SyncTaskService;
import com.sync.platform.service.RestoreTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * Home controller for dashboard
 */
@Controller
public class HomeController {

    @Autowired
    private ServerConfigService serverConfigService;
    
    @Autowired
    private DatabaseConfigService databaseConfigService;
    
    @Autowired
    private SyncTaskService syncTaskService;
    
    @Autowired
    private SyncTaskLogService syncTaskLogService;
    
    @Autowired
    private RestoreTaskService restoreTaskService;

    /**
     * Home page
     */
    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("pageTitle", "同步平台 - 首页");
        return "index";
    }

    /**
     * Dashboard page
     */
    @GetMapping("/dashboard")
    public String dashboard(Model model) {
        // Count servers
        int serverCount = serverConfigService.countServers();
        model.addAttribute("serverCount", serverCount);
        
        // Count databases
        int databaseCount = databaseConfigService.countDatabases();
        model.addAttribute("databaseCount", databaseCount);
        
        // Count sync tasks (both database and file sync)
        int dbSyncCount = syncTaskService.countDatabaseSyncTasks();
        int fileSyncCount = syncTaskService.countFileSyncTasks();
        int taskCount = dbSyncCount + fileSyncCount;
        model.addAttribute("taskCount", taskCount);
        
        // Count today's syncs
        LocalDateTime startOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        LocalDateTime endOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
        int todaySyncCount = syncTaskLogService.countLogsBetween(startOfDay, endOfDay);
        model.addAttribute("todaySyncCount", todaySyncCount);
        
        // Get recent logs
        model.addAttribute("recentLogs", syncTaskLogService.getRecentLogs(10));
        
        model.addAttribute("pageTitle", "同步平台 - 仪表盘");
        return "dashboard";
    }
}
